package com.phenix.wanandroid

import android.app.Application
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import androidx.lifecycle.ProcessLifecycleOwner
import com.phenix.network.base.BaseNetworkApi
import com.phenix.network.environment.INetworkRequired
import com.phenix.network.error.BusinessException
import com.phenix.network.response.NetworkResponseAdapterFactory
import com.tencent.mmkv.MMKV

class App : Application() {

    companion object {
        private const val TAG = "App"
    }

    override fun onCreate() {
        super.onCreate()

        val result = MMKV.initialize(this)
        Log.i(TAG, "MMKV init: $result")

        BaseNetworkApi.apply {
            val isDevelop = MMKV.defaultMMKV().decodeBool(Constants.KEY_ENV_DEVELOP, true)
            Log.i(TAG, "isDevelop: $isDevelop")
            init(isDevelop, object : INetworkRequired {
                override fun getAppVersionName(): String {
                    return BuildConfig.VERSION_NAME
                }

                override fun getAppVersionCode(): Int {
                    return BuildConfig.VERSION_CODE
                }

                override fun isDebugMode(): Boolean {
                    return BuildConfig.DEBUG
                }

                override fun getApplicationContext(): Application {
                    return this@App
                }

            })

            setGlobalErrorHandler(object : NetworkResponseAdapterFactory.FailureHandler {
                override fun onFailure(throwable: BusinessException): Boolean {
                    Log.e(TAG, "onFailure:$throwable")
                    return false
                }

            })
        }

        ProcessLifecycleOwner.get().lifecycle.addObserver(AppLifecycleObserver())

    }

    private class AppLifecycleObserver : LifecycleObserver {

        // 方法名随便取，注解才是重点
        @OnLifecycleEvent(Lifecycle.Event.ON_START)
        fun onForeground() {
            Log.i(TAG, "应用回到前台")
        }

        @OnLifecycleEvent(Lifecycle.Event.ON_STOP)
        fun onBackground() {
            Log.i(TAG, "应用退到后台")
        }
    }

}